using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Common;
using Common.Converters;
using Common.Extensions;
using Common.Filter;
using Common.Job;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Repository;
using Service;
using Service.Converters;
using Snowflake.Net;

namespace WebApp
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddService(Configuration)
                .AddDbContextPool<TestDbContext>(Configuration)
                .AddxxlJobs(Configuration)
                .AddControllers(options =>
                {
                    // 注册全局过滤器
                    options.Filters.Add<GlobalExceptionFilter>();
                    options.Filters.Add<TokenAuthenticationFilter>();
                }).AddJsonOptions(options =>
                {
                    var serviceProvider = services.BuildServiceProvider();
                    var dictService = serviceProvider.GetService<IDictService>();
                    // 注册自定义转换器
                    options.JsonSerializerOptions.Converters.Add(new GenericAwareConverter(dictService));
                    //忽略循环引用
                    options.JsonSerializerOptions.IgnoreReadOnlyProperties = true;
                    options.JsonSerializerOptions.Converters.Add(new DatetimeJsonConverter());
                    // 注册long类型转换器
                    options.JsonSerializerOptions.Converters.Add(new LongJsonConverter());
                    // 注册可空long?类型转换器（如果需要）
                    options.JsonSerializerOptions.Converters.Add(new NullableLongJsonConverter());
                });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment()) app.UseDeveloperExceptionPage();

            app.UseXxlJobExecutor(Configuration);

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
        }
    }
}